package cn.edu.hbpu.service.impl;

import cn.edu.hbpu.common.R;
import cn.edu.hbpu.dto.CartDto;
import cn.edu.hbpu.dto.GoodsDto;
import cn.edu.hbpu.entity.Cart;
import cn.edu.hbpu.entity.Goods;
import cn.edu.hbpu.handler.CustomException;
import cn.edu.hbpu.mapper.CartMapper;
import cn.edu.hbpu.mapper.GoodsMapper;
import cn.edu.hbpu.service.CartService;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpStatus;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private CartMapper cartMapper;

    @Autowired
    private GoodsMapper goodsMapper;


    @Override
    public R<List<CartDto>> getUserCartItems(String userId) {
        // 1. 检测用户id是否传入
        if (StrUtil.isBlank(userId)) {
            throw new CustomException("请传入用户id");
        }
        // 2. 根据用户id查询到用户的购物车列表
        LambdaQueryWrapper<Cart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Cart::getUserId, userId);
        List<Cart> carts = cartMapper.selectList(queryWrapper);
        // 3. 遍历购物车列表并根据商品gId查询出商品信息，并将cart信息和goods信息复制到CartDto中
        List<CartDto> cartDtoList = carts.stream().map(cart -> {
            Goods goods = goodsMapper.selectById(cart.getGId());
            CartDto cartDto = new CartDto();
            BeanUtil.copyProperties(goods, cartDto);
            BeanUtil.copyProperties(cart, cartDto);
            return cartDto;
        }).collect(Collectors.toList());

        return new R<>(HttpStatus.HTTP_OK, cartDtoList);
    }

    @Override
    public R<String> changeChecked(Cart cart) {
        // 1. 获取checked，gId，userId三个值
        Integer checked = cart.getChecked();
        String gId = cart.getGId();
        String userId = cart.getUserId();
        // 2. 判断三个值是正确的值
        if (StrUtil.isBlank(gId) || StrUtil.isBlank(userId)) {
            throw new CustomException("请传入gId或userId");
        }
        if (checked != 1 && checked != 0) {
            throw new CustomException("请传入正确的checked值");
        }
        // 3. 更新某个商品选中状态
        LambdaUpdateWrapper<Cart> queryWrapper = new LambdaUpdateWrapper<>();
        queryWrapper.eq(Cart::getUserId, userId);
        queryWrapper.eq(Cart::getGId, gId);
        queryWrapper.set(Cart::getChecked, checked);
        int res = cartMapper.update(null, queryWrapper);
        System.out.println(res);
        return new R<>(HttpStatus.HTTP_OK, "修改checked成功");
    }

    @Override
    public R<String> changeAllChecked(CartDto cartDto) {
        // 1. 获取userId，checked，gIdList三个值
        String userId = cartDto.getUserId();
        Integer checked = cartDto.getChecked();
        List<CartDto> cartGoodsList = cartDto.getCartGoodsList();
        // 2. 判断三个值是正确的值
        if (Objects.isNull(cartGoodsList) || StrUtil.isBlank(userId)) {
            throw new CustomException("请传入cartGoodsList或userId");
        }
        if (checked != 1 && checked != 0) {
            throw new CustomException("请传入正确的checked值");
        }
        // 3. 更新所有商品选中状态
        cartGoodsList.forEach((item) -> {
            item.setChecked(cartDto.getChecked());
            this.changeChecked(item);
        });
        return new R<>(HttpStatus.HTTP_OK, "修改所有商品checked成功");
    }

    @Override
    public R<String> deleteCartGoods(CartDto cartDto) {
        // 1. 获取用户id
        String userId = cartDto.getUserId();
        // 2. 获取要删除的购物车商品列表
        List<CartDto> goodsList = cartDto.getCartGoodsList();
        // 3. 循环删除购物车商品
        goodsList.forEach((item) -> {
            LambdaQueryWrapper<Cart> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Cart::getUserId, userId);
            queryWrapper.eq(Cart::getGId, item.getGId());
            cartMapper.delete(queryWrapper);
        });
        return new R<>(HttpStatus.HTTP_OK, "删除购物车商品成功");
    }

    @Override
    public R<String> updateGoodsAmount(Cart cart) {
        // 1. 获取userId，gId，amount
        String userId = cart.getUserId();
        String gId = cart.getGId();
        Long amount = cart.getAmount();
        // 2. 判断三个值是正确的值
        if (StrUtil.isBlank(userId) || StrUtil.isBlank(gId)) {
            throw new CustomException("请传入gId或userId");
        }
        if (amount <= 0) {
            throw new CustomException("商品数量必须大于0");
        }
        // 3. 根据修userId和gId修改购物车中商品的数量
        LambdaUpdateWrapper<Cart> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Cart::getUserId, userId);
        updateWrapper.eq(Cart::getGId, gId);
        updateWrapper.set(Cart::getAmount, amount);
        cartMapper.update(null, updateWrapper);
        return new R<>(HttpStatus.HTTP_OK, "修改购物车商品数量成功");
    }

    @Override
    public R<String> addGoodsToCart(GoodsDto goodsDto) {
        // 1. 获取要插入到购物车的字段
        // 商品数量
        Long count = goodsDto.getCount();
        // 用户id
        String userId = goodsDto.getUserId();
        // 商品id
        String gId = goodsDto.getGId();

        // 2. 检查字段是否正确
        if (count <= 0) {
            throw new CustomException("商品购买数量不能为0");
        }
        if (StrUtil.isBlank(userId)) {
            throw new CustomException("用户Id不能为空");
        }
        if (StrUtil.isBlank(gId)) {
            throw new CustomException("商品Id不能为空");
        }

        // 3. 检查该商品是否已经存在购物车中
        LambdaQueryWrapper<Cart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Cart::getGId, gId);
        Cart cart = cartMapper.selectOne(queryWrapper);
        if (cart == null) {
            // 4. 若没有存在，则插入数据到购物车表中
            Cart newCart = new Cart();
            newCart.setUserId(userId);
            newCart.setChecked(0);
            newCart.setGId(gId);
            newCart.setAmount(count);
            int res = cartMapper.insert(newCart);
            // 5. 根据结果判断是否插入成功
            if (res >= 1) {
                return new R<>(HttpStatus.HTTP_OK, "加入购物车成功");
            } else {
                throw new CustomException("加入购物车成功失败");
            }
        } else {
            // 6. 若已经存在，则将购买数量加一
            // 先查询出该商品，然后再其购物数量的基础上加一
            cart.setAmount(cart.getAmount()+count);
            LambdaUpdateWrapper<Cart> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(Cart::getGId, gId);
            cartMapper.update(cart, updateWrapper);
            return new R<>(HttpStatus.HTTP_OK, "加入购物车成功");
        }

    }
}
